import axios from 'axios'
import {
  MessageBox,
  Message,
  Loading
} from 'element-ui'
import store from '@/store'
import {
  getToken
} from '@/utils/auth'
let gb_loading
const loading_conf = {
  background: '#1515154d'
}
let base_url = window.location.protocol + '//' + window.location.host
// console.log(base_url, process.env.VUE_APP_DEBUG)
if (process.env.VUE_APP_DEBUG) {
  base_url = process.env.VUE_APP_BASE_API
}
// create an axios instance
const service = axios.create({
  baseURL: base_url, // url = base url + request url
  // baseURL: '/api/', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // jwt
      config.headers['passport'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    gb_loading&&gb_loading.close()
    /** 验证 token */
    if (res.status === 2) {
      MessageBox.confirm(res.msg,
        'Confirm logout', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
        store.dispatch('admin/delete_token').then(() => {
          let cs=this.$store.state.user.model=='shop'?'a=&':''
          this.$router.push(`/login?${cs}redirect=${this.$route.fullPath}`);
        })
      })
    }
    /** 业务逻辑未通过 */
    if (res.status === 0) {
    /** 业务逻辑未通过 */
      Message({
        message: res.msg,
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(res)
    } else if (res.status === 1) {
      /** 通过返回数据 */
      return res.data
    }
  },
  error => {
    gb_loading&&gb_loading.close()
    // console.log('err' + error) // for debug
    Message({
      message: error.msg,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export function get(url, _data = {}, method = 'get') {
  gb_loading = Loading.service(loading_conf)
  let params; let data = {}
  if (method === 'get') {
    params = _data
  } else {
    data = _data
  }
  return service({
    url: url,
    method: method,
    params: params,
    data: data
  })
}

export default service
